package com.tanhua.dubbo.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.domain.db.AnalysisByDay;
import com.tanhua.domain.db.Log;
import com.tanhua.dubbo.api.db.LogApi;
import com.tanhua.dubbo.mapper.AnalysisByDayMapper;
import com.tanhua.dubbo.mapper.LogMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;

@DubboService
public class LogApiImpl implements LogApi {

    @Autowired
    private LogMapper logMapper;
    @Autowired
    private AnalysisByDayMapper analysisByDayMapper;
    @Override
    public void save(Log log) {
        logMapper.insert(log);
    }

    @Override
    public void analysis(String todayStr) {
//        tb_log
//        新注册用户数
        Integer numRegistered =  logMapper.queryRegisterOrLoginNum(todayStr,"0102");
//        select count( DISTINCT user_id ) as num  from tb_log where log_time='2021-11-19' and type='0102'
//        登陆次数
//        select count( DISTINCT user_id ) as num  from tb_log where log_time='2021-11-19' and type='0101'
        Integer numLogin =  logMapper.queryRegisterOrLoginNum(todayStr,"0101");
//        活跃用户数
//        select count( DISTINCT user_id ) as num  from tb_log where log_time='2021-11-19'
        Integer numActive =  logMapper.queryActiveNum(todayStr);
//        次日留存用户数
//        select count( DISTINCT user_id  ) as num  from tb_log where log_time='2021-11-19'
//        and user_id in  (  select   user_id   from tb_log where log_time='2021-11-18' and type='0102')

        String yesTodayStr = DateTime.parse(todayStr).minusDays(1).toString("yyyy-MM-dd");
        Integer numRetention1d =  logMapper.queryRetention1dNum(todayStr,yesTodayStr);
//        构建 AnalysisByDay对象保存

//        先判断今天是否有analysisByDay数据 如果有更新 如果没有新增
        QueryWrapper<AnalysisByDay> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AnalysisByDay::getRecordDate,DateTime.parse(todayStr).toDate());
        AnalysisByDay analysisByDay = analysisByDayMapper.selectOne(queryWrapper);

        if(analysisByDay==null){
            analysisByDay = new AnalysisByDay();
            analysisByDay.setRecordDate(DateTime.parse(todayStr).toDate());
            analysisByDay.setNumRegistered(numRegistered);
            analysisByDay.setNumActive(numActive);
            analysisByDay.setNumLogin(numLogin);
            analysisByDay.setNumRetention1d(numRetention1d);
            analysisByDayMapper.insert(analysisByDay);
        }else{
            analysisByDay.setNumRegistered(numRegistered);
            analysisByDay.setNumActive(numActive);
            analysisByDay.setNumLogin(numLogin);
            analysisByDay.setNumRetention1d(numRetention1d);
            analysisByDayMapper.updateById(analysisByDay);
        }




    }
}
